//
//  CycleBanner.swift
//  E-CycleForShop
//
//  Created by enghou on 17/3/2.
//  Copyright © 2017年 xyxorigation. All rights reserved.
//  有非常隐蔽的bug😄看你能不能发现
//pic	String	"https://www.elerecycle.com:443/erecycle/medias/activitypicture/vk1490181200605.png"
import UIKit
protocol helpBannerTurn : NSObjectProtocol {
    func turn(url : String) -> Void
}
class CycleBanner: BaseView,UICollectionViewDelegate,UICollectionViewDataSource,UIScrollViewDelegate {

    weak var delegate : helpBannerTurn?
    let page = UIPageControl.init()
    
    var source : Array<BannerItemModel> = []{
        didSet{
            reloadData()
        }
    }
    
    private var collection : UICollectionView?
    
    private var currentIndex = 0
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.backgroundColor = UIColor.white
        self.configCollection()
    }
    
    init(frame: CGRect,imgArr : Array<BannerItemModel>) {
        super.init(frame: frame)
        self.configCollection()
        source = imgArr
    }
    
    func reloadData() -> Void {
        collection!.reloadData()
        collection!.contentOffset = CGPoint.init(x: CGFloat(source.count * 5000) * YXDeviceWidth, y: 0)
        page.numberOfPages = source.count
        page.frame = CGRect.init(origin: CGPoint.init(x: 60 * YXWidthScale, y: self.bounds.height - 52 * YXHeightScale), size: CGSize.init(width: 72 * YXWidthScale, height: 12 * YXHeightScale))
        page.currentPage = 0
    }
    
    func autoCycle(interval : TimeInterval) -> Void {
        let timer = Timer.init(timeInterval: interval, target: self, selector: #selector(cycle), userInfo: nil, repeats: true)
        RunLoop.current.add(timer, forMode: .defaultRunLoopMode)
    }
    
    @objc func cycle() -> Void {
        if source.count > 0 {
            let target = collection!.contentOffset.x + YXDeviceWidth
            collection!.setContentOffset(CGPoint.init(x: target, y: 0), animated: true)
            let idx = target / YXDeviceWidth
            page.currentPage = Int(idx) % source.count
        }
    }
    
    private func configCollection()->Void{
        let layout = UICollectionViewFlowLayout.init()
        layout.itemSize = frame.size
        layout.scrollDirection = .horizontal
        layout.minimumInteritemSpacing = 0
        layout.minimumLineSpacing = 0
        collection = UICollectionView.init(frame: self.bounds, collectionViewLayout: layout)
        collection!.delegate = self
        collection!.dataSource = self
        collection!.showsHorizontalScrollIndicator = false
        collection?.backgroundColor = UIColor.white
        collection!.register(BannerCell.classForCoder(), forCellWithReuseIdentifier: "cycle")
        self.addSubview(collection!)
        collection!.isPagingEnabled = true
        page.pageIndicatorTintColor = UIColor.init(red: 80 / 255, green: 80 / 255, blue: 80 / 255, alpha: 1)
        page.currentPageIndicatorTintColor = UIColor.white
        self.addSubview(page)
    }
    
    //代理方法
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cycle", for: indexPath)
        let idx = indexPath.row % source.count
        let cel = cell as! BannerCell
        cel.model = source[idx]
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 10000 * source.count
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        collectionView.deselectItem(at: indexPath, animated: true)
        let idx = indexPath.row % source.count
        self.delegate?.turn(url: source[idx].url)
    }
    
    func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
        
    }
    
    
    func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
        if decelerate == false {
            let index = scrollView.contentOffset.x / YXDeviceWidth
            let idx = Int(index) % source.count
            page.currentPage = idx
        }
    }
    
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        //停止滑动时根据滑动位移重置滑动位移,并设置page
        let index = scrollView.contentOffset.x / YXDeviceWidth
        let idx = Int(index) % source.count
        page.currentPage = idx
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

}
